/**
 * 使用页面
 * add_order
 * modify_order
 */
export default {
  props: {},
  data () {
    return {
      rulesBasic: {
        name: [
          {
            required: true,
            message: '请输入申请人姓名',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入申请人联系电话',
            trigger: 'blur'
          },
          {
            min: 11,
            message: '联系电话必须达到11位',
            trigger: 'blur'
          }
        ],
        type: [
          {
            required: true,
            message: '请选择出库类型',
            trigger: 'change'
          }
        ],
        detail: [
          {
            required: true,
            message: '请输入详细地址',
            trigger: 'blur'
          }
        ],
        orgName: [
          {
            required: true,
            message: '请选择部门',
            trigger: 'blur'
          }
        ]
      },
      fullscreenLoading: false,
      copyTable: [], // 拷贝列表数据
      buyNumber: '',
      dealWithNew: 0,
      getMoney: '',
      lastTime: 0, // f防抖使用
      routeQuery: {}, // 路由参数
      customerIntention: '', // 客户意向
      moreSpecification: '', // 存多规格row值
      paymentAmount: '', // 在线支付金额
      payStatus: '', // 在线支付
      setPay: {
        payDefault: '', // 设为默认
        payment: ''
      },
      setCloseOrder: '', // 关闭订单弹框选择理由的值
      whether: false, // 是否禁用
      auditStatus: '', // 是否必审值，1：必审，0：非必审
      quantity: '', // 数量
      uprice: '', // 单价
      addressDataList: [], // 收货地址数据
      siteDataList: [], // 订单地址数据
      clientMessage: {}, // 客户基本信息

      // 新增收货地址参数校验
      rules: {
        userName: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' },
          {
            validator: function (rule, value, callback) {
              // console.log('存在中文', /^[\u4e00-\u9fa5]|^[a-zA-Z]/.test(value))
              // console.log('存在英文', /[a-zA-Z]+$/.test(value))
              // if (/^[\u4e00-\u9fa5]+$/.test(value) == false) {
              if (/^[\u4e00-\u9fa5]+$/.test(value) === false && /[a-zA-Z]+$/.test(value) === false) {
                // callback(new Error('请输入中文'))
                callback(new Error('请输入有误'))
              } else {
                // 校验通过
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { min: 11, max: 11, message: '请填写11位数的联系电话', trigger: 'blur' }
        ],
        addressValue: [
          { required: true, message: '请选择地址', trigger: 'change' }
        ],
        detailedAddress: [
          { required: true, message: '请输入详细地址', trigger: 'change' }
        ]
      },
      // 新增收货地址参数
      form: {
        userName: '', // 姓名
        phone: '', // 联系电话
        provinceCode: '', // 省
        cityCode: '', // 市
        regionCode: '', // 区
        detailedAddress: '', // 详细地址
        addressValue: [],
        isDefault: 0
      },
      selectPayData: '', // 支付方式值
      selectPay: '',
      payType: '',
      radioForm: { resource: '' },
      stepsActive: 1, // 步骤条状态
      num: 1,

      specificationList: '', // 多规格组合数据
      titleNum: {}, // tab标题数量
      dialog: { visible: false, title: '', width: '', type: '' },
      stepsData: {
        active: 0,
        list: ['选购商品', '提交订单', '支付订单', '提交审核']
      },
      breadcrumbConfig: {
        list: [
          {
            title: '我的客户',
            type: '#ff0000',
            path: '/'
          },
          {
            title: '修改订单',
            type: '1',
            path: ''
          }
        ]
      },
      searchFormVal: {},
      searchFormConfig: {
        formconfig: {
          labeWidth: 70, // 表单宽度
          itemList: [// 表单的list
            { type: 'input', prop: 'name', placeholder: '请输入内容', label: '商品名称', size: 'small' },
            { type: 'input', prop: 'goodsNo', placeholder: '请输入内容', label: '商品编号', size: 'small' },
            {
              type: 'cascaderCategory',
              prop: 'categoryId',
              placeholder: '请选择内容',
              label: '商品类目',
              size: 'small',
              showAllLevels: false,
              option: [{ label: '选择一', value: 'key1' }, { label: '选择二', value: 'key2' }]
            },
            {
              type: 'select', prop: 'brandId', placeholder: '请选择内容', label: '品牌', size: 'small', showAllLevels: false,
              option: [{ label: '选择一', value: 'key1' }, { label: '选择二', value: 'key2' }]
            }
          ],
          btnarry: [// 表单按钮
            { name: '查询', click: 'add', type: 'primary', plain: true, size: 'small' },
            { name: '重置', click: 'clrear', type: 'primary', plain: true, size: 'small' }
          ]
        },
        formData: { // 表单提交数据，
          checkbox: []// 注：如果类型是checkbox，必须foemData里边提前声明数组
        }
      },
      goods: { name: '', brand: '', category: [], code: '' },
      activeName: 'goods',
      total: 0,
      giftPrice: 0,
      receivedMoney: 0,
      tableData: [],
      currentPage1: 1,
      pageSizegoods: 10,
      currentPageZp: 1,
      pageSizeZp: 10,
      id: '',
      brandselect: [],
      options: [],
      addressId: '',
      goodsL: [],
      giftL: [],
      orderNumber: 0,
      origTotal: 0, // 原价
      arry: [],
      arrayZp: [],
      taskId: '',
      isChange: '', // 判断是否是修改的订单
      orderId: '',
      textarea: '',
      pingZ: false,
      imageUrl: '',
      Img: '',
      fileList: [],
      voucher: '',
      channelOrderId: '', // 分配条件开单
      tabIndex: 0,
      page: { list: [], pageNo: 1, pageSize: 10, totalNum: 0, currentPage: 1 },
      columns: [
        { label: '序号', type: 'index', width: '60', prop: 'index' },
        { label: '商品编号', prop: 'goodsNo' },
        {
          label: '商品图片',
          width: '200',
          render: (h, scope) => {
            return (
              <div>
                <el-image src={scope.row.mainImage} preview-src-list={scope.row.mainImageArr}></el-image>
              </div>
            )
            // <img style='width: 150px; height: 150px' src={scope.row.mainImage}></img>
          }
        },
        { label: '商品名称', prop: 'name' },
        { label: '商品品牌', prop: 'brandName' },
        { label: '商品类目', prop: 'categoryName' },
        { label: '商品类型', prop: 'goodsType' },
        {
          label: '价格',
          sortable: true,
          prop: 'marketPrice',
          render: (h, scope) => {
            return (
              <span>￥{scope.row.marketPrice}</span>
            )
          }
        },
        { label: '商品规格', prop: 'specification' },
        {
          label: '可用库存', prop: 'stock', sortable: 'custom',
          render: (h, scope) => {
            return (
              <span>{scope.row.stock}</span>
            )
          }
        },
        //  <div>
        //         <el-link
        //           size='mini'
        //           type='primary'
        //           onClick={() => { this.addOrder(scope.row, scope.$index) }}>添加商品</el-link>
        //       </div>
        {
          label: '操作',
          render: (h, scope) => {
            return (
              <el-button type='text' style='color:409EFF' slot='reference' onClick={() => {
                this.moreCombination(scope.row, scope.$index)
              }}>添加商品</el-button>
            )
          }
        }]
    }
  },
  computed: {
    // 应付价格
    dealWith: {
      get () {
        let dealWithTwo = 0
        for (const item of this.orderDetailList) {
          // console.log(item, 'item')
          dealWithTwo += item.quantity * Number(item.retailPrice)
        }
        return dealWithTwo
      },
      set (newValue) {
        this.dealWith = newValue
      }
    },
    // 商品总价格
    totalPrice () {
      let totalPrice = 0
      for (const item of this.orderDetailList) {
        totalPrice += item.quantity * Number(item.marketPrice)
      }
      return totalPrice
    },
    totalNumber () {
      let totalNumber = 0
      for (const item of this.orderDetailList) {
        totalNumber += item.quantity
      }
      return totalNumber
    }
  },
  watch: {
    dictionaries: {
      handler (newVal, oldVal) {
        // this.setSearchDictionaries('商品类型', 'goods_type')
      },
      deep: true // 为true，表示深度监听
    },
    orderDetailList: {
      handler (newVal, oldVal) {
        newVal.forEach(item => {
          item.totalRetailPrice = item.retailPrice * item.quantity
          item.totalMarketPrice = item.marketPrice * item.quantity
        })
      },
      deep: true // 为true，表示深度监听
    },
    dealWith: {
      handler (newVal, oldVal) {
        this.dealWithNew = newVal
      }
    }
  },
  created () {
  },
  methods: {
    // 确定选择支付方式
    handlerSelectPay () {
      if (this.selectPay) {
        this.selectPayData = this.selectPay
        this.activeSubmit()
      }
    },
    fetchData (type) {
      // const params = Object.assign({}, this.searchFormVal)
      const tabIndex = this.tabIndex
      const page = this.page
      const data = {
        name: '', //	否	string	商品名称
        goodsNo: '', //	否	string	商品编号
        categoryId: '', //	否	String	类目id（数据来源：接口 - /order/comm/commodityCategory/commList）
        brandId: '', //	否	int	品牌id（数据来源：接口 - 待开发）
        orderBy: '', //	否	int	排序（0价格；1可用库存）
        orderByType: '', //	否	int	排序方式（0正序；1倒序）
        pageNo: page.pageNo, //	否	int	当前页码（从1开始）
        pageSize: page.pageSize //	否	int	单页记录数（默认10）
      }
      const params = Object.assign(data, this.searchFormVal)
      if (params.categoryId) {
        params.categoryId = params.categoryId[params.categoryId.length - 1]
      }
      // if (params.brandId) { params.brandId = params.brandId[params.brandId.length - 1] }
      // 去除字符串 前后 空格
      for (const item in params) {
        if (typeof params[item] === 'string') {
          params[item] = params[item].trim()
        }
      }
      //	否	int	类型（1：普通商品；2：虚拟商品；3：赠品；字典：goods_type）
      params.goodsType = tabIndex == 0 ? '1' : '3'
      if (params.goodsType == 1) {
        params.isGift = false
      }
      if (params.goodsType == 3) {
        params.isGift = true
      }
      this.$api.selectPlaceGoodsPageList(params).then((res) => {
        if (res.code === 0) {
          res.data.list.forEach((item) => {
            if (item.mainImage && item.mainImage.indexOf('http') !== 0) {
              item.mainImage = this.ImgHttps + item.mainImage
            }

            item.mainImageArr = []
            item.mainImageArr.push(item.mainImage)
            // item.mainImage = item.mainImage+'-150x150'
            if (item.goodsSpecList) {
              let tempSpec = ''
              item.goodsSpecList.forEach((itemb) => {
                tempSpec += `${itemb.name}(${itemb.specItemList.length}) 、`
              })
              item.specification = tempSpec
              if (item.specification.length > 0) {
                item.specification = item.specification.substring(0, item.specification.length - 1)
              }
            }
            item.marketPrice = Number(item.marketPrice)
            item.stock = Number(item.stock)
          })
          this.page.list = res.data.list
          this.copyTable = res.data.list
          this.page.totalNum = res.data.totalNum
          this.getPlaceGoodsCount(params) // 选购商品数量统计查询接口
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    handleCurrentChange (currentChange) {
      this.page.pageNo = currentChange
      this.fetchData()
    },
    handleSizeChange (sizeChange) {
      this.page.currentPage = 1
      this.page.pageSize = sizeChange
      this.fetchData()
    },
    // 初始化搜索数据 - 类目id
    initSearchCategoryList () {
      const params = { pageNo: 1, pageSize: 1000 }
      this.$api.brandDate(params).then((res) => {
        if (res.code == 0) {
          // res.data.list.forEach(item => {
          //   // item.label = item.categoryName
          //   item.value = item.id
          // })
          const index = this.searchFormConfig.formconfig.itemList.findIndex(e => {
            return e.label === '商品类目'
          })
          this.searchFormConfig.formconfig.itemList[index].option = res.data.list
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 初始化搜索数据 - 品牌
    initSearchBrandList () {
      const params = { pageNo: 1, pageSize: 1000 }
      this.$api.selectList(params).then((res) => {
        if (res.code === 0) {
          // console.log(res, 'resss')
          res.data.forEach(item => {
            item.label = item.name
            item.value = item.id
          })
          const index = this.searchFormConfig.formconfig.itemList.findIndex(e => {
            return e.label === '品牌'
          })
          this.searchFormConfig.formconfig.itemList[index].option = res.data
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 回
    back () {
      this.stepsActive = 1
    },
    getPassFlag () {
      const params = { funcCode: 1 }
      this.$api.getPassFlag(params).then((res) => {
        if (res.code == 0) {
          this.auditStatus = res.data
          if (res.data == 1) { // 等于1默认是否必审为是，并禁用
            this.radioForm.resource = '1'
            this.whether = true
          } else if (res.data == 0) { // 等于0默认是否必审为否，并可以随意选择是、否
            this.radioForm.resource = '0'
            this.whether = false
          } else {
            this.radioForm.resource = 0
          }
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    handleSort ({ column, prop, order }) {
      // prop：排序的字段、order：升序（ascending）、降序（descending）、取消排序（null）
      const copyTableDate = this.page.list // 拷贝表格数据
      let reserveData = [] // 过滤后保留的数据
      const filterData = [] // 过滤掉的数据
      // 开始进行数据过滤：将'--'过滤到filterData数组中，剩余数值型数据保留到reserveData中。
      copyTableDate.forEach(item => {
        if (item[prop] === 'stock') { // item[prop]：将要排序那个字段的值
          filterData.push(item) // item：表格中的这条数据，即row
        } else {
          reserveData.push(item)
        }
      })
      // 排序
      if (order !== null) {
        if (order === 'descending') { // 降序
          // 冒泡排序
          reserveData = reserveData.sort((a, b) => b[prop] - a[prop])
        } else { // 升序
          reserveData = reserveData.sort((a, b) => a[prop] - b[prop])
        }
        // 过滤掉的数据添加到数组末尾
        filterData.forEach(item => {
          reserveData.push(item)
        })
        this.page.list = reserveData
      } else {
        // 取消排序
        // this.copyTable是在接口得到表格数据的时候拷贝了一份，用来还原取消排序时的表格数据
        this.page.list = this.copyTable
      }
    },
    getNumber (customerId) {
      // console.log(customerId)
      // const params = { customerId }
      const params = { customerId: customerId || this.$route.query.userId }
      this.$api.getNumber(params).then((res) => {
        if (res.code == 0) {
          this.buyNumber = res.data
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    open () {
      this.$alert('未选择客户，请返回我的客户页面选择客户下单！', {
        confirmButtonText: '确定',
        callback: action => {
          this.$router.push({ name: '/customers/list' })
          this.$message({
            type: 'warning ',
            message: `action: ${action}`
          })
        }
      })
    },
    // 已收价格输入框失去焦点方法
    handlerReceivedMoney () {
      if (this.receivedMoney && this.receivedMoney > this.dealWithNew) {
        this.receivedMoney = this.dealWithNew
      }
    },
    // 内部出库生成订单
    activeSubmitType (basic) {
      this.$refs[basic].validate((valid) => {
        if (valid) {
          console.log(this.basic, 'this.basic')
          if (this.orderDetailList.length === 0) {
            return this.$message.warning('请选择商品！')
          }
          if (this.stepsActive === 1) {
            if (!this.basic.province && !this.basic.city && !this.basic.area) {
              this.$message.warning('地区信息不能为空')
              return
            }
            if (this.receivedMoney && this.receivedMoney > 0 || this.receivedMoney == 0) {
              this.stepsActive = 2
              return
            } else {
              return this.$message.warning('请填写已收金额！')
            }
          }
          if (this.stepsActive === 2) {
            const params = {
              address: this.basic.province + this.basic.city + this.basic.area, // 地址选择的省市区组合的名字
              addressDetails: this.basic.detail, // 详细地址
              anew: this.$route.query.type, // 是否是第一次出单
              awaitIncomeMoney: this.totalPrice - this.receivedMoney, // 待收款
              charge: 0, // 运费
              city: this.basic.city, // 市
              comment: this.textarea, // 备注
              consignee: this.basic.name, // 收货人
              consigneeDepaCode: typeof (this.basic.orgName) === 'string' ? this.basic.orgName : this.basic.orgName[this.basic.orgName.length - 1], // 部门编号
              money: this.totalPrice, // 金额
              orderCommodityAdds: this.orderDetailList, //	是	object[]	订单详情列表
              pieceNumber: this.totalPrice, // 积分
              province: this.basic.province, // 省
              receivedMoney: this.receivedMoney, // 已收款
              receivingPhone: this.basic.phone, // 收货电话
              region: this.basic.area, // 区
              total: this.totalPrice, // 总金额
              typeId: this.basic.type // 出库类型id
            }
            // if (this.$route.query.awaitSubmit || this.$route.query.type) {
            //   delete params.platformOrderNo
            //   params.id = this.modifyOrderDetails.id
            // }
            const loading = this.$loading({
              lock: true,
              text: '正在加载中...'
            })
            this.$api.addInteriorOrder(params).then((res) => {
              if (res.code == 0) {
                this.$notify({
                  title: '成功',
                  message: '提交 数据 成功 ！',
                  type: 'success'
                })
                loading.close()
                const query = { refresh: true, state: 99, nowTime: new Date().getTime() }
                // console.log(query)
                this.$router.push({ name: 'InternalList', query })
              } else {
                loading.close()
              }
              console.log(this.orderDetailList, 'this.orderDetailList')
            }).catch((err) => {
              console.log(err)
            })
          }
        } else {
          this.$message.warning('申请人信息未填写完整')
          return false
        }
      })
    },
    // 下单页面生成订单
    activeSubmit () {
      console.log(this.$route.query.platformId, 'this.$route.query.platformId')
      if (this.orderDetailList.length === 0) {
        return this.$message.warning('请选择商品！')
      }
      if (this.stepsActive === 1) {
        if (this.receivedMoney && this.receivedMoney > 0 || this.receivedMoney == 0) {
          this.stepsActive = 2
          return
        } else {
          return this.$message.warning('请填写已收金额！')
        }
      }
      if (this.stepsActive === 2) {
        if (this.siteDataList.length == 0) {
          return this.$message.warning('请添加收货地址！')
        }
        this.dialog.type = 'selectPayNew'
        this.dialog.title = '选择支付方式'
        this.dialog.visible = true
        this.dialog.width = '450px'
        if (this.selectPayData == '') {
          return
        } else {
          this.dialog.visible = false
        }

        const sysUserId = sessionStorage.getItem('user_id')
        const params = {
          userId: this.customerId, //	是	int	客户id
          sysUserId, //	是	int	跟进客服id
          userIntention: this.customerIntention, //	是	int	客户意向（http://120.24.147.235:8087/sys/v1/common/by/group?groupId=customer_intention）
          remarks: this.textarea, //	否	string	备注
          platformId: this.$route.query.platformId ? this.$route.query.platformId : '25', //	否	int	下单平台（默认为：25）
          orderType: 1, //	否	int	订单类型（字典：order_main_type 1.普通订单 2.虚拟商品订单 3.电子券（poi核销） 4.三方核销）
          customerAddressId: this.siteDataList[0].id, //	否	int	收货地址id
          // payType: this.setPay.payment, //	是	string	支付方式（字典：order_pay_type）1.在线支付（支付宝、微信）2.代收3.货到付款
          payType: this.selectPayData, //	是	string	支付方式（字典：order_pay_type）1.在线支付（支付宝、微信）2.代收3.货到付款
          quantity: this.totalNumber, //	是	string	商品总数
          freightAmount: 0, //	是	string	运费
          totalAmount: this.totalPrice, //	是	double	商品总价
          changeAmount: 0, //	否	double	改单金额
          receivableAmount: this.dealWithNew, //	是	string	应收金额（商品总价 + 运费 + 改单金额 - 优惠金额）
          discountAmount: 0, //	是	string	优惠金额
          receivedAmount: this.receivedMoney, //	是	string	实收金额
          collectionAmount: this.totalPrice - this.receivedMoney, //	是	string	（物流）代收金额（应收金额 - 实收金额）
          afterSalesStatus: '0', //	是	string	售后状态（0无售后；1售后进行中；2售后完成）
          approveStatus: this.radioForm.resource, //	是	string	审核状态（0无审核/审核完成；1审核中）
          orderDetailList: this.orderDetailList, //	是	object[]	订单详情列表
          platformOrderNo: this.orderNo //	否	string	平台关联订单号
        }
        if (this.$route.query.awaitSubmit || this.$route.query.type) {
          delete params.platformOrderNo
          params.id = this.modifyOrderDetails.id
        }
        const loading = this.$loading({
          lock: true,
          text: '正在加载中...'
        })
        this.$api.placeOrder(params).then((res) => {
          if (res.code == 0) {
            this.$notify({
              title: '成功',
              message: '提交 数据 成功 ！',
              type: 'success'
            })
            this.selectPay = ''
            loading.close()
            const query = { refresh: true, state: 99, nowTime: new Date().getTime() }
            // console.log(query)
            this.$router.push({ name: 'ordersList', query })
          } else {
            loading.close()
          }
          console.log(this.orderDetailList, 'this.orderDetailList')
        }).catch((err) => {
          console.log(err)
        })
      }
    }
  }
}
